package com.raylu.day03basic;

import com.raylu.utils.IntSource;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

public class Example2TypeErasing2 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        // 1 --> (1,1,1)
        // (1,1,1) + null --> (1,1,1)
        // 2 --> (2,2,2)
        // (2,2,2) + (1,1,1) --> (1,2,3)
        env
                .addSource(new IntSource())
                .map(r -> Tuple3.of(r, r, r))
                .returns(Types.TUPLE(Types.INT, Types.INT, Types.INT))
                .keyBy(r -> 1)
                .reduce(new ReduceFunction<Tuple3<Integer, Integer, Integer>>() {
                    @Override
                    public Tuple3<Integer, Integer, Integer> reduce(Tuple3<Integer, Integer, Integer> value1, Tuple3<Integer, Integer, Integer> value2) throws Exception {
                        return Tuple3.of(
                                value1.f0 < value2.f0 ? value1.f0 : value2.f0,
                                value1.f1 > value2.f1 ? value1.f1 : value2.f1,
                                value1.f2 + value2.f2
                        );
                    }
                })
                .print();

        env.execute();
    }
}